package com.example.e_comm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.e_comm.entity.Permission;
import com.example.e_comm.mapper.PermissionMapper;
import com.example.e_comm.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Transactional
public class PermissionServiceImpl
        extends ServiceImpl<PermissionMapper, Permission>
        implements PermissionService {
    @Autowired
    private PermissionMapper mapper;
    
    @Override
    public List<Permission> getPermissionByPage(Page<Permission> page) {
        return mapper.selectList(page, null);
    }
    
    @Override
    public IPage<Permission> getPermissionByPageWithCount(Page<Permission> page, String keyword) {
        QueryWrapper<Permission> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(keyword)){
            wrapper.like("perm_name", keyword)
                    .or().like("perm_key", keyword);
        }
        return mapper.selectPage(page, wrapper);
    }
    
    @Override
    public List<Permission> getPermissionByUserId(Long userId) {
        return mapper.getPermissionByUserId(userId);
    }
    
    @Override
    public List<Permission> getPermissionByRoleId(Long roleId) {
        return mapper.getPermissionsByRoleId(roleId);
    }
    
    @Override
    public Set<String> getPermissionByUserIdSet(Long userId) {
        List<Permission> list = getPermissionByUserId(userId);
        return list.stream()
                .map(Permission::getPermKey)
                .collect(Collectors.toSet());
    }
    
    @Override
    public Set<String> getPermissionByRoleIdSet(List roleId) {
        // 根据角色ID列表获取权限键集合
        Set<String> permissionKeys = new java.util.HashSet<>();
        for (Object rid : roleId) {
            if (rid instanceof Long) {
                List<Permission> permissions = getPermissionByRoleId((Long) rid);
                permissionKeys.addAll(permissions.stream()
                        .map(Permission::getPermKey)
                        .collect(Collectors.toSet()));
            }
        }
        return permissionKeys;
    }
}